# -*- coding: utf-8 -*-
# Project : flacon
# File : ogg_encoder.py
# (c) Alexander Sokolov sokoloff.a@gmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.



import encoder
import errors
from settings import *
from flaconglobal import *
from PyQt4 import QtCore
import sys, re

import ogg_config

class OggEncoder(encoder.Encoder):
    id = 'OGG'
    extension = 'ogg'
    name = 'OGG'

   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def trackGainClass(cls):
        return OggGain


   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def configPageClass(cls):
        return ogg_config.OggConfig


   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def programs(cls):
        return ['oggenc']


   #****************************************************************
   #
   #****************************************************************
    def getEncoderArgs(self):
        args = QStringList()
        args << settings.value("Programs/oggenc").toString()
        args << "--quiet"

        # Quality settings .........................................
        if settings.value("Ogg/UseQuality").toBool():
            args << "-q" << settings.value("Ogg/Quality").toString()
        else:
            val = settings.value("Ogg/NormBitrate").toString()
            if val:
                args << "-b" << val

            val = settings.value("Ogg/MinBitrate").toString()
            if val:
                args << "-m" << val

            val = settings.value("Ogg/MaxBitrate").toString()
            if val:
                args << "-M" << val

        # Tags .....................................................
        if (self._track.artist()):  args << "--artist"  << self._track.artist()
        if (self._track.album()):   args << "--album"   << self._track.album()
        if (self._track.genre()):   args << "--genre"   << self._track.genre()
        if (self._track.year()):    args << "--date"    << str(self._track.year())
        if (self._track.title()):   args << "--title"   << self._track.title()
        if (self._track.comment()): args << "--comment" << QString("COMMENT=%1").arg(self._track.comment())
        if (self._track.discId()):  args << "--comment" << QString("DISCID=%1").arg(self._track.discId())
        args << "--tracknum" << str(self._track.trackNum())
        args << "--comment" << QString("TOTALTRACKS=%1").arg(self._track.trackSet().count())
        args << "--comment" << QString("TRACKTOTAL=%1").arg(self._track.trackSet().count())

        # Files ....................................................
        args << "-o" << self._outFile,
        args << "-"
        return args



class OggGain(encoder.Gain):


   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def programs(cls):
        return ['vorbisgain']


   #****************************************************************
   #
   #****************************************************************
    def getArgs(self):
        args = QStringList()
        args << settings.value("Programs/vorbisgain").toString()
        if settings.value("Ogg/ReplayGain") == ReplayGainTypes.Album:
            args << "--album"

        args << self._files

        return args


   #****************************************************************
   #
   #****************************************************************
    def parseOut(self, proc):
        buff = ''
        trackName = ''

        calcRe = re.compile(r"^\s*(\d{1,3})%\s*-\s*(.*)")

        while True:
            if self._cancel:
                proc.terminate()
                proc.wait()
                raise errors.Abort()

            c = proc.stderr.read(1)
            if not c: break
            buff += c
            #sys.stdout.write(c)

            if (c == "\r"):
                r = calcRe.search(buff)
                if (r):
                    if trackName != r.groups()[1]:
                        trackName = r.groups()[1]
                        n = self._files.indexOf(QString(trackName).trimmed())
                        if n>-1:
                            self._trackIndex = self._trackIndexses[n]

                    percent = int(r.groups()[0])
                    self.progressChanged(Statuses.CalcGain, percent)

                buff = ''



#****************************************************************
# Register encoder & gain classes
#****************************************************************
encoder.registerEncoder(OggEncoder)
